import json
import requests
from bs4 import BeautifulSoup


def json_parser(getter=None):
    def out_wrapper(func):
        def wrapper(*args, **kwargs):
            result = func(*args, **kwargs)
            # 校验返回值的合法性
            if result.status_code != 200:
                raise Exception("http返回码错误!")
            if getter is None:
                return result.text
            return getter(json.loads(result.text))
        return wrapper
    return out_wrapper


def xml_parser(getter=None):
    def out_wrapper(func):
        def wrapper(*args, **kwargs):
            result = func(*args, **kwargs)
            # 校验返回值的合法性
            if result.status_code != 200:
                raise Exception("http返回码错误!")
            if getter is None:
                return result.text
            return getter(BeautifulSoup(result.text, "lxml"))
        return wrapper
    return out_wrapper


class BaseSpider:
    session = requests.session()
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36"
    }
    host = ""

    @staticmethod
    def city(city):
        return {
            "杭州": "hz",
            "上海": "sh",
            '北京': 'bj',
            '成都': 'cd',
            '重庆': 'cq',
            '长沙': 'cs',
            '东莞': 'dg',
            '大连': 'dl',
            '佛山': 'fs',
            '广州': 'gz',
            '合肥': 'hf',
            '南京': 'nj',
            '青岛': 'qd',
            '深圳': 'sz',
            '苏州': 'su',
            '沈阳': 'sy',
            '天津': 'tj',
            '武汉': 'wh',
            '厦门': 'xm'
        }[city]

    def _url(self, url_path: str):
        return f"{self.host}/{url_path}"

    def get(self, uri: str, params=None):
        return self.session.get(self._url(uri), params=params, headers=self.headers)
